import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';

import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';

import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import Detail from './Detail';
import './../Home/openlayers.less';
import AddOrEditMeter from './AddOrEditMeter';
import PressConfig from './PressConfig';
import ReactDataGrid from 'react-data-grid';
import AddOrEditVendor from '../Vendor_meter/AddOrEditVendor';
const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;

@connect(({ pressure_sensors, loading,global }) => ({
  pressure_sensors,
  global,
  loading: loading.models.pressure_sensors,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      pressure_sensors: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        pressure_sensors: {  searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'pressure_sensors/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'pressure_sensors/changeLoaded',
          });
          dispatch({
            type: 'pressure_sensors/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'pressure_sensors/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'pressure_sensors/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }
  findChildFunc = (cb)=> {
    this.findChildLocation = cb
  }
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'pressure_sensors/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      pressure_sensors: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="传感器名称">
          {getFieldDecorator('name', {
            initialValue: searchParams.name,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="IMEI">
          {getFieldDecorator('imei', {
            initialValue: searchParams.imei,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="安装地址">
          {getFieldDecorator('address', {
            initialValue: searchParams.address,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>

        <FormItem label="在线状态">
          {getFieldDecorator('online_status', {
            initialValue: searchParams.online_status,
          })(
            <Select style={{width:'100px'}}>
              <Option value="0">全部</Option>
              <Option value="1">在线</Option>
              <Option value="-1">离线</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        pressure_sensors: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
        });

      });
    }
  }

  handleAdd = () => {
    const location= this.findChildLocation();
    console.log('location',location)
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'pressure_sensors/add',
      payload: {
        ...formValues,
        longitude:location[0],
        latitude:location[1],
      },
      callback() {
        message.success('添加压力传感器成功');
        that.setState({
          addModal: false,
        });
        const {
          pressure_sensors: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      name:'',
      imei:'',
      address:'',
      online_status:'0',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const location= this.findChildLocation();
    console.log('location',location)
    const formValues = this.EditForm.props.form.getFieldsValue();

    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `pressure_sensors/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
        longitude:location[0],
        latitude:location[1],
      },
      callback() {
        message.success('修改压力传感器成功');
        that.setState({
          editModal: false,
        });
        const {
          pressure_sensors: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleConfig = () => {
    const formValues = this.configForm.props.form.getFieldsValue();

    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `pressure_sensors/editConfig`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改压力传感器配置成功');
        that.setState({
          configModal: false,
        });
        const {
          pressure_sensors: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `pressure_sensors/remove`,
      payload: { id },
      callback: () => {
        message.success('删除水表成功');
        const {
          pressure_sensors: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case 1:
        type = 'check-circle', color = '#004cff', text = '在线';
        break;
      case -1:
        type = 'close-circle', color = '#fe1b2e', text = '离线';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };

  render() {
    const that = this;
    const {
      pressure_sensors: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global:{gridTableW}
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        formatter: (event) => {
          const {
            pressure_sensors: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page-1)*meta.per_page)+(event.value+1)}</p>
        }
      },
      {
        name: '压力传感器名称',
        width: 130,
        key: 'name',

      },
      {
        name: 'IMEI',
        key: 'imei',
        width: 150,
      },
      {
        name: '在线状态',
        key: 'online_status',
        width: 100,
        formatter: (event) => {
          return this.renderStatus(event.value)
        }
      },
      {
        name: '最新上传数据时间',
        width: 200,
        key: 'upload_time',
        formatter: (event) => {
          return event.row.pressure_data.upload_time
        }
      },
      {
        name: '最新压力(MPA)',
        width: 110,
        key: 'pressure',
        formatter: (event) => {
          return <p className={event.row.pressure_data.pressure_status===0?'table-success table-status':'table-error table-status' }>{event.row.pressure_data.pressure}</p>
        }
      },
      {
        name: '最新电压(V)',
        width: 100,
        key: 'voltage',
        formatter: (event) => {
          return event.row.pressure_data.voltage
        }
      },
      {
        name: '操作',
        width: 300,
        key: 'right',
        classname:'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
          {
            find(this.permissions, { name: "pressure_sensor_operation" }) &&
              <Fragment>
                <Button
                  type="primary"
                  size="small"
                  icon="setting"
                  onClick={(e) => {
                    this.setState({
                      editRecord: event.row,
                      configModal: true,
                    });
                  }
                  }
                >配置
                </Button>
                <Button
                  type="primary"
                  size="small"
                  icon="edit"
                  onClick={(e) => {
                    e.stopPropagation();
                    this.setState({
                      editRecord: event.row,
                      editModal: true,
                    });
                  }
                  }
                >编辑
                </Button>
                <Button
                  type="danger"
                  size="small"
                  icon="delete"
                  onClick={(e) => {
                    e.stopPropagation();
                    confirm({
                      title: `确定要删除"${event.row.name}"吗?`,
                      content: '请谨慎操作！',
                      okText: '确定',
                      okType: 'danger',
                      cancelText: '取消',
                      centered:true,
                      maskClosable: true,
                      onOk() {
                        that.handleDelete(event.row.id);
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    });
                  }
                  }
                >删除
                </Button>
              </Fragment>
          }



        </Fragment>,
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if(totalWidth<gridTableW){
      columns[columns.length-1].width=   columns[columns.length-1].width+gridTableW-totalWidth
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>压力监测站点</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item">
            <p>压力传感器总数量(个)</p>
            <h4>{meta.total}</h4>
          </div>
          {
            find(this.permissions, {name: "pressure_sensor_operation"})&&
            <div size="large" className="table-info-right-item">
              <Button
                icon="plus"
                style={{ marginLeft: 8 }}
                type="primary"
                onClick={
                  () => {
                    this.setState({
                      addModal: true,
                    });
                  }
                }
              >
                添加压力传感器
              </Button>
            </div>
          }

        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {return {...data[i],_index:i}}}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                if(!String(row)){
                  return
                }
                this.props.dispatch({
                  type: 'pressure_sensors/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading&&<Loading />
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`添加压力传感器`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            addModal: false,
            editRecord: {},
          });
        }}
        width={700}
        visible={this.state.addModal}
      >
        <AddOrEditMeter
          onClose={() => {
            this.setState({
              addModal: false,
              editRecord: {},
            });
          }}
          findChildFunc={this.findChildFunc}
          onSave={this.handleAdd}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />
      </Drawer>
      <Drawer
        title={`修改压力传感器 ${this.state.editRecord.name} `}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            editModal: false,
            editRecord: {},
          });
        }}
        width={700}
        visible={this.state.editModal}
      >
        <AddOrEditMeter
          onClose={() => {
            this.setState({
              editModal: false,
              editRecord: {},
            });
          }}
          editRecord={this.state.editRecord}
          findChildFunc={this.findChildFunc}
          onSave={this.handleEdit}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />
      </Drawer>
      <Drawer
        title={`${this.state.editRecord.name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={700}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.id}></Detail>
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.configModal} modalClass="configModal"
                                title={`${this.state.editRecord.name} 修改配置`}/>}
        destroyOnClose
        visible={this.state.configModal}
        centered
        onOk={this.handleConfig}
        className="configModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ configModal: false, editRecord: {} });
        }}

      >
        <PressConfig
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.configForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
